var express = require('express')
const {
  addMessageService,
  findMessageByPageService,
  deleteMessageService,
  findDayNumOfMessageService,
  findBlogsCommentByPageService,
  delBlogsCommentService
} = require('../service/messageService')
const { ipv6ToV4,formatResponse} = require('../utils/tool')
var router = express.Router()

// 添加留言或者评论
router.post('/', async function (req, res, next) {
  //获取请求ip并记录数据库
  let ip =
    req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    ''
  // 通过正则判断是否是ipv6
  let ipv6Reg = /:/g
  let ipv4 = ip
  if (ipv6Reg.test(ip)) {
    ipv4 = ipv6ToV4(ip)
  }
  console.log(ip, '<--ip')
  req.body.ip = ipv4
  //查询当日的留言数量
  let num = await findDayNumOfMessageService(ipv4)
  console.log(num, '<--当然留言条数');
  if(num >= 3){ 
    res.send(formatResponse(1,"每日留言数量已达上限",{}))
    return
  }
  res.send(await addMessageService(req.body))
})

// 获取留言或者评论
router.get('/', async function (req, res, next) {
  res.send(await findMessageByPageService(req.query))
})

// 删除留言或者评论
router.delete('/:id', async function (req, res, next) {
  res.send(await deleteMessageService(req.params.id))
})
//分页获取博客楼层留言
router.get('/getBolgsComment',async(req,res) => {
  res.send(await findBlogsCommentByPageService(req.query))
})
//删除博客楼层留言
router.post('/delBlogsComment',async(req,res) => {
  res.send(await delBlogsCommentService(req.body))
})
module.exports = router
